import { service } from "@/utils/request";
import { ElMessage } from "element-plus";
import router from "@/router";
import { post } from "@/api/http";

/**
 * @description 用户登录
 */
//对应RequestBody的请求
export function login(loginForm) {
  return service({
    method: "post",
    url: "/api/user/login", //加上前缀api
    data: {
      phone: loginForm.phone,
      code: loginForm.code,
      password: loginForm.password,
    }, //返回结果
  }).then((res) => {
    if (res.data.success) {
      localStorage.setItem("token", res.data.data);
      ElMessage.success("登录成功");
      let promise = router.push("/");
    } else {
      ElMessage.error("登录失败");
    }
  });
}

//经GPT提示，封装上述请求为：
/**
 * @description GPT
 */

// Function to handle user login
export async function gpt_login(loginForm) {
  try {
    const response = await post("/api/user/login", {
      phone: loginForm.phone,
      code: loginForm.code,
      password: loginForm.password,
    });
    if (response.data.success) {
      localStorage.setItem("token", response.data.data);
      ElMessage.success("登录成功");
      await navigateToHomePage();
    } else {
      ElMessage.error("登录失败");
    }
  } catch (error) {
    ElMessage.error("登录失败");
    console.error(error);
  }
}

/**
 * @description Helper function to navigate to the home page
 */

async function navigateToHomePage() {
  try {
    await router.push("/");
  } catch (error) {
    console.error("Failed to navigate to the home page:", error);
  }
}

/**
 * @description 验证码请求
 * @param phone
 * @returns {Promise<AxiosResponse<any>>}
 */
//对应RequestParam的请求
export function code(phone) {
  return service({
    method: "post",
    url: "/api/user/code",
    params: {
      phone: phone,
    },
  }).then((response) => {
    if (response.data.success) {
      ElMessage.success("验证码已发送，请查收");
    } else {
      ElMessage.error("请求验证码失败");
    }
  });
}

/**
 *
 * @param phone
 * @returns {Promise<void>}
 */
export async function requestVerificationCode(phone) {
  try {
    const response = await service.post(`/api/user/code?phone=${phone}`);
    console.log(response);
    if (response.data.success) {
      ElMessage.success("验证码已发送，请查收");
    } else {
      ElMessage.error("请求验证码失败");
    }
  } catch (error) {
    ElMessage.error("请求验证码失败");
    console.error(error);
  }
}
